import {Component, OnInit} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ActivatedRoute} from "@angular/router";
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
// import * as jspdf from 'jspdf';
// import html2canvas from 'html2canvas';
import { BiService } from '../../bi.service';
@Component({
  selector: 'apes-today-insurance-order-total',
  templateUrl: './apes-today-insurance-order-total.component.html',
  styleUrls: ['./apes-today-insurance-order-total.component.scss']
})
export class ApesTodayInsuranceOrderTotalComponent implements OnInit {
  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  height: any = window.innerHeight - 480 + 'px';

  // 饼图相关
  salesPieData: any;
  xinbao = [];
  xubao = [];
  xin : any;
  xu : any;

  sevenData: any[];    // 柱型图相关

  endDate = null;      // 默认结束时间
  startDate = null;    // 默认开始时间 当天的前7天

  endTime = null;      // 传的结束时间
  startTime = null;    // 传的起始时间

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];

  startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private routerInfo: ActivatedRoute,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "日期", field: 'RQ'},
      {headerName: "新保数", field: 'XIN'},
      {headerName: "续保数", field: 'XU'},
      {headerName: "人保", field: 'RB'},
      {headerName: "人寿", field: 'RS'},
      {headerName: "总报价车辆", field: 'BJZS'},
      {headerName: "待支付订单", field: 'DZF'},
      {headerName: "订单数量", field: 'YZF'},
      {headerName: "成交均价", field: 'CJPJJG'},
      {headerName: "成交总金额", field: 'CJZJE'},
      {headerName: "到店报价", field: 'DDBJ'},
      {headerName: "报价成交率", field: 'BJCJL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 7天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (7 * 24 * 60 * 60 * 1000));
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this._submit();
  }

  _submit() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.xinbao = [];
    this.xubao = [];
    this.xin = 0;
    this.xu = 0;
    // 传的时间 进行转换
    if(this.endDate !== null && this.startDate !== null) {
      this.startTime = (this.startDate.toISOString()).slice(0, 10);
      this.endTime = (this.endDate.toISOString()).slice(0, 10);
      this.getTablesData();
    }else {
      this.msg.error('日期必填，不能为空！');
    }
  }

  getTablesData() {
    let data = {
      'interfaceMethod': 'ipmBusinessStatementService.getJrbxxsdd',
      'pdata': {'ZDRQ_SJ': this.startTime, 'SKRQ_SJ': this.endTime, 'companyId': this.companyList}
    };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj)
            this.rowData = data;
            data = data.sort(this.sortarr('RQ'));
            for (let i = 0, len = data.length; i < len; i++) {
              this.xinbao.push(data[i].XIN);
              this.xubao.push(data[i].XU);
            }
            // 饼图 新保数据获取
            for (let i = 0, len = this.xinbao.length; i < len; i++) {
              this.xin += this.xinbao[i];
            }
            // 饼图 续保数据获取
            for (let i = 0, len = this.xubao.length; i < len; i++) {
              this.xu += this.xubao[i];
            }
            //柱型图 数据获取
            const sevenList = data.slice(0, data.length);
            this.sevenData = sevenList.map((value) => {
              return { x: value['RQ'], y: value['CDS'] };
            });
            // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      {x: '新保数', y: this.xin},
      {x: '续保数', y: this.xu},
    ];
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }


  // onCaptureScreen() {
  //   const data = document.getElementById('pdf');
  //   html2canvas(data).then(canvas => {
  //     // Few necessary setting options
  //     const imgWidth = 208;
  //     const pageHeight = 295;
  //     const imgHeight = canvas.height * imgWidth / canvas.width;
  //     const heightLeft = imgHeight;
  //
  //     const contentDataURL = canvas.toDataURL('image/png')
  //     const pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
  //     const position = 0;
  //     pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
  //     pdf.save('MYPdf.pdf'); // Generated PDF
  //   });
  // }
}
